from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
import uvicorn
import logging
from contextlib import asynccontextmanager
import time
import os

from app.config import settings
from app.routers import (
    tasks_json as tasks,
    monitoring_json as monitoring,
    auth_json as auth,
    websocket_json as websocket
)
from app.models.schemas import APIResponse
from app.storage.json_storage import storage

# 配置日志
logging.basicConfig(
    level=getattr(logging, settings.LOG_LEVEL.upper()),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时初始化
    try:
        # 确保数据目录存在
        os.makedirs("data", exist_ok=True)
        logger.info("JSON storage initialized successfully")
        logger.info(f"Application started in {'DEBUG' if settings.DEBUG else 'PRODUCTION'} mode")
    except Exception as e:
        logger.error(f"Failed to initialize application: {e}")
        raise

    yield

    # 关闭时清理资源
    try:
        logger.info("Application shutdown completed")
    except Exception as e:
        logger.error(f"Error during shutdown: {e}")

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    description="网站数据爬取任务管理系统后端API",
    version=settings.VERSION,
    docs_url="/api/docs" if settings.DEBUG else None,
    redoc_url="/api/redoc" if settings.DEBUG else None,
    lifespan=lifespan
)

# 中间件配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=settings.ALLOWED_HOSTS
)

# 请求日志中间件
@app.middleware("http")
async def log_requests(request: Request, call_next):
    start_time = time.time()
    
    # 记录请求信息
    logger.info(f"Request: {request.method} {request.url}")
    
    response = await call_next(request)
    
    # 记录响应信息
    process_time = time.time() - start_time
    logger.info(f"Response: {response.status_code} - {process_time:.3f}s")
    
    return response

# 全局异常处理
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    """HTTP异常处理"""
    return JSONResponse(
        status_code=exc.status_code,
        content=APIResponse(
            success=False,
            message=exc.detail,
            error_code="HTTP_ERROR"
        ).model_dump()
    )

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    """请求验证异常处理"""
    errors = []
    for error in exc.errors():
        field = " -> ".join(str(x) for x in error["loc"])
        message = error["msg"]
        errors.append(f"{field}: {message}")
    
    return JSONResponse(
        status_code=422,
        content=APIResponse(
            success=False,
            message="请求参数验证失败",
            error_code="VALIDATION_ERROR",
            data={"errors": errors}
        ).model_dump()
    )

@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """全局异常处理"""
    logger.error(f"Unhandled exception: {exc}", exc_info=True)
    
    return JSONResponse(
        status_code=500,
        content=APIResponse(
            success=False,
            message="服务器内部错误" if not settings.DEBUG else str(exc),
            error_code="INTERNAL_SERVER_ERROR"
        ).model_dump()
    )

# 路由注册
app.include_router(
    auth.router, 
    prefix="/api/v1/auth", 
    tags=["认证"]
)

app.include_router(
    tasks.router, 
    prefix="/api/v1/tasks", 
    tags=["任务管理"]
)

app.include_router(
    monitoring.router, 
    prefix="/api/v1", 
    tags=["监控"]
)

app.include_router(
    websocket.router, 
    prefix="/api/v1/ws", 
    tags=["WebSocket"]
)

# 根路径和健康检查
@app.get("/")
async def root():
    """根路径"""
    return APIResponse(
        message=f"欢迎使用 {settings.APP_NAME}",
        data={
            "version": settings.VERSION,
            "docs_url": "/api/docs" if settings.DEBUG else None,
            "status": "running"
        }
    )

@app.get("/api/v1/health")
async def health_check():
    """健康检查"""
    return APIResponse(
        message="服务运行正常",
        data={
            "status": "healthy", 
            "version": settings.VERSION,
            "debug": settings.DEBUG
        }
    )

# 获取API信息
@app.get("/api/v1/info")
async def get_api_info():
    """获取API信息"""
    return APIResponse(
        message="API信息",
        data={
            "name": settings.APP_NAME,
            "version": settings.VERSION,
            "debug": settings.DEBUG,
            "endpoints": {
                "auth": "/api/v1/auth",
                "tasks": "/api/v1/tasks",
                "monitoring": "/api/v1",
                "websocket": "/api/v1/ws",
                "docs": "/api/docs" if settings.DEBUG else None
            }
        }
    )

if __name__ == "__main__":
    uvicorn.run(
        "app.main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG,
        log_level=settings.LOG_LEVEL.lower(),
        access_log=True
    )
